<!DOCTYPE html>
<html>

<head>
    <!-- <script src="./htmlparser.js"></script> -->
</head>

<body>
    <script>
        function calculate(str) {
            let stack = [],tmp = '',ex = ''
            for (let i = 0; i <= str.length; i++) {
                let ch = str[i]
                if (ch === ' ') continue
                // 获取数字
                if (ch >= '0' && ch <= '9') {
                    for(let j = i;j<str.length;j++){
                        if(str[j]<'0' || str[j] > '9'){
                            ch = str.substring(i,j)
                            i = j - 1
                            break
                        }
                    }
                }
                if(ch >= '0' && ch <= '9'){
                    ex += ch + ' '
                }else if(/[\+\-\(]/.test(ch)){
                    stack.push(ch)
                }else if(ch === ')'){
                    
                    while((tmp = stack.pop()) !== '(' && stack.length > 0){
                        ex += tmp
                    }
                }
            }
            while(stack.length > 0){
                ex += stack.pop()
            }
            for (let index = 0; index < ex.length; index++) {
                let ch = ex[index]
                if (ch === ' ') continue
                if(ch >= '0' && ch <= '9'){
                    for(let j = index;j<ex.length;j++){
                        if(ex[j] === ' '){
                            ch = ex.substring(index,j)
                            index = j -1
                            break
                        }
                    }
                    stack.push(Number(ch))
                } else {
                    let item1 = stack.pop() || 0
                    let item2 = stack.pop() || 0
                    switch(ch){
                        case '+':
                            stack.push(item1 + item2);
                            break;
                        case '-':
                            stack.push(item2 - item1)
                            break
                    }
                }
            }
            return stack.pop()
        }
        function expect (str){
            console.log(calculate(str),eval(str))
            return calculate(str) === eval(str)
        }
        // console.log(expect(`(1+(4+5+2)-3)+(6+8)`))
        // console.log(expect(`- (13 + (4 + 5))`)) 
        // console.log(expect(`  1 + 3 + 5   `))
        console.log(expect(` 2-1 + 2 `)) 
    </script>
</body>

</html>